﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.ServiceProcess;
using System.Text;
using SignalR;
using SignalR.Hosting.Self;
using SignalR.Hubs;

namespace Live.Refresh.Service
{
    public partial class Service1 : ServiceBase
    {
        private readonly FileSystemWatcher _fileSystemWatcher;
        private IObservable<EventPattern<FileSystemEventArgs>> _observable;
        public Service1()
        {
            InitializeComponent();
            _fileSystemWatcher = new FileSystemWatcher { Path = @"C:\", IncludeSubdirectories = true};
        }

        protected override void OnStart(string[] args)
        {
            string url = System.Configuration.ConfigurationManager.AppSettings["server"];
            var server = new Server(url);

            server.MapHubs();

            // Start the server
            server.Start();
            
            _fileSystemWatcher.EnableRaisingEvents = true;

            IHubContext clHub = GlobalHost.ConnectionManager.GetHubContext<LiveRefresh>();
            _observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
               h => _fileSystemWatcher.Changed += h,
               h => _fileSystemWatcher.Changed -= h);

            _observable.Throttle(TimeSpan.FromSeconds(2)).Select(c=> c.EventArgs)
            .Subscribe(ep => clHub.Clients.Refresh(ep.FullPath));
        }

        protected override void OnStop()
        {
            
        }
    }
    public class FileWatcherHub : Hub
    {
        private readonly FileSystemWatcher _fileSystemWatcher;
        //private IObservable<EventPattern<FileSystemEventArgs>> _observable;
        private IDisposable unsubscribe;

        public FileWatcherHub()
        {
            _fileSystemWatcher = new FileSystemWatcher { Path = @"C:\", IncludeSubdirectories = true };
        }

        public void StartWatch()
        {
             unsubscribe = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
               h => _fileSystemWatcher.Changed += h,
               h => _fileSystemWatcher.Changed -= h).Throttle(TimeSpan.FromSeconds(2)).Select(x=> x.EventArgs)
            .Subscribe(ep => Clients.Refresh(ep.FullPath));
        }
        public void StopWatch()
        {
            unsubscribe.Dispose();
        }
    }
}
